<?php

namespace App\Http\Controllers\Admin\Goods;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Http\Controllers\Common\CommonApi;
use App\Http\Requests\Goods\Goodsrequest;
use Illuminate\Support\Facades\Redis;
use App\Http\Controllers\Home\Search\SearchController;
use App\Model\Goods;
use App\Model\Gdescr;
use App\Model\Brand;
use App\Model\Sort;
use App\Model\Gdetails_pic;
use App\Model\Gshow;
use App\Model\Gprice;
use App\Model\Carousels;
use DB;

/**
 * @author chenxinbin<xinbin882@gmail.com>
 * 后台商品的控制器(增删改查)
 */
class GoodsController extends Controller
{
     /**
     * 显示商品详情页
     *
     * @return 调转到product-list.blade.php中并带去参数 $goods
     */
    public function index()
    {

        $goods = Goods::select(['goods.id', 'goods.goods_sn', 'goods.gname', 'brand.bname',  'sort.sname', 'goods.price', 'goods.click', 'goods.pic','goods.state'])
                    ->join('brand', 'goods.bid', '=', 'brand.id')
                    ->join('sort', 'goods.sid', '=', 'sort.id')
                    ->orderBy('goods.id', 'asc')
                    ->paginate(5);
        
        return view ('Admin/Goods/product-list', ['goods' => $goods]);

    }

    /**
     * 显示添加商品的页面
     *
     * @return  调转到product-add.blade.php中并带去参数$brands和$catagorys
     */
    public function create()
    {
       
        $catagorys = Sort::select('id', 'sname', 'pid', 'path')->orderBy(DB::raw('concat(path, id)'))->get();
        foreach ($catagorys as $key => $value) {
            $value['nbsp'] = str_repeat("&nbsp;",substr_count($value['path'],",")*6); 
        }
        $brands = Brand::select(['id', 'bname'])->get();
        
        return view ("Admin/Goods/product-add",['catagorys' => $catagorys, 'brands' => $brands]);
      
    }

    /**
     * 添加商品到goods表
     *
     * @param  接收到上传的数据
     * @return 添加成功跳转到路由admin/goods 添加失败返回失败的位置
     */
    public function store(Goodsrequest $request)
    {
        $sid = $request->input('sid');
        $piddata = Sort::select(['pid', 'id'])->where('id', $sid)->first();
        $pid =$piddata->pid;
        if($pid == '0')
            {
                return back()->with('errorTip', '分类不能为根分类如男鞋，女鞋，童鞋'); 
            }
        $common = new CommonApi;
        $res = $common->uploadToQiNiu($request, 'file_upload');
        if($res['status'] == 4403){
                 return $res['msg'];
        }
        $pic = "http://owv3oi69q.bkt.clouddn.com/".$res['data']['key'];
        $launch_time = time();
        $id = Goods::insertGetId([
                'gname' => $request->input('gname'),
                'goods_sn' => $request->input('goods_sn'),
                'bid' => $request ->input('bid'),
                'sid'=> $request->input('sid'),
                'price'  => $request ->input('price'),
                'unit'   => $request ->input('unit'),
                'click'    => $request ->input('click'),
                'state' => $request ->input('state'),
                'is_member_price' => $request ->input('is_member_price'),
                'score' => $request ->input('score'),
                'launch_time' =>$launch_time,
                'pic' => $pic,
                'created_at' => date('Y-m-d H:i:s', time()),
                'updated_at' => date('Y-m-d H:i:s', time()),
                ]);
        $bool = Gprice::insert([
                'gid'=>  $id,
                'color' => $request->input('color'),
                'size' =>$request->input('size'),
                'price' =>$request->input('price'),
                'discount_price' =>$request->input('price'),
                'storage' =>$request->input('storage'),
                'sales' =>$request->input('sales'),
                'is_discount' => 2,
                'created_at' => date('Y-m-d H:i:s', time()),
                'updated_at' => date('Y-m-d H:i:s', time()),
                 ]);
        $info = Gdescr::insert([
                'gid'=>  $id,
                'state' => $request ->input('state'),
                'descr' => $request ->input('descr'),
                'created_at' => date('Y-m-d H:i:s', time()),
                'updated_at' => date('Y-m-d H:i:s', time()),
                ]);
        // dd($info);
        $search = new SearchController();
        $xunsearch =$search->addToXunSearch($id);//将数据添加到讯搜中

        if($id & $bool & $info){
                Redis::del('lazyLoad:0');
                Redis::del('lazyLoad:1');
                Redis::del('lazyLoad:2');
                Redis::del('lazyLoad:3');
                Redis::del('lazyLoad:4');
                Redis::hDel('hotData', 'hotData:'.$id);

                // dd(1);
                return redirect('Admin/goods')->with('msg', '添加成功');

        }else{

                return back()->with('errorTip', '添加失败,系统出错请稍后重试');

        }
    }

    /**
     * Display the specified resource.
     * @author wuboheng
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */

    public function show($id)
    {   
        //根据商品id查询商品表(goods表)
        $goods = Goods::select(['goods.id as id', 'goods_sn', 'gname', 'price', 'unit', 'sales', 'click', 'pic', 'launch_time', 'drop_time', 'is_member_price', 'score', 'goods.state', 'brand.bname as bname', 'sort.sname as sname'])
            ->join('brand', 'goods.bid', '=', 'brand.id')
            ->join('sort', 'goods.sid', '=', 'sort.id')
            ->where('goods.id', $id)
            ->first()
            ->toArray();

        // dd($goods);

        //根据商品的id查询商品详细数据(goods_price表)
        $goods_details = Goods::find($id)
            ->findGoodsPrice()
            ->get()
            ->toArray();

        // dd($goods_details);

        return view('Admin/Goods/product-detail', [
            'goods' => $goods,
            'goods_details' => $goods_details,

        ]);
    }

    /**
     * 显示编辑商品页面
     *
     * @param  int  $id
     * @return 返回视图product-edit并带去数据
     */
    public function edit($id)
    {
        $oneProduct = Goods::select(['goods.id', 'goods.click', 'goods.bid', 'goods.sid', 'goods.goods_sn', 'goods.gname', 'goods.price', 'goods.sales', 'goods.pic','goods.is_member_price', 'goods.score', 'brand.bname','goods_descr.descr', 'goods_descr.state'])
                    ->join('brand', 'brand.id' , '=', 'goods.bid')
                    ->join('goods_descr', 'goods_descr.gid', '=', 'goods.id')
                    ->where('goods.id', $id)
                    ->first();
        // dd($oneProduct);
        $allBrands = Brand::select(['bname', 'id'])->get();
        $allSorts = Sort::select(['id', 'sname', 'pid', 'path'])->orderBy(DB::raw('concat(path, id)'))->get();
        foreach ($allSorts as $key => $value) {

            $value['nbsp'] = str_repeat("&nbsp;",substr_count($value['path'],",")*6); 
        }
        // dd($allSorts);
        return view('Admin/Goods/product-edit', [
            'oneProduct' => $oneProduct, 
            'allBrands' => $allBrands,
            'allSorts' => $allSorts
            ]);
        
    }

    /**
     * 处理编辑后过来的的数据并保存到数据库
     *
     * @param  编辑的数据
     * @param  int  $id
     * @return 成功返回路由Admin/Goods，错误返回原来的位置
     */
    public function update(Request $request, $id)
    {

        $sid = $request->input('sid');
        $piddata = Sort::select(['pid', 'id', 'path'])->where('id', $sid)->first();
        $path =$piddata->path;
        if($path == '0')
            {
                return back()->with('errorTip', '分类不能为根分类如男鞋，女鞋，童鞋'); 
            }
        foreach($request->files as $pic)
        {
           $pathinfo=$pic;
        }
        $old_pic = Goods::select('id','pic')->where('id', $id)->first();
        $oldpic =$old_pic->pic;
        if(empty($pathinfo)){
                $pic = $oldpic;
        } else {
            $common = new CommonApi;
            $res = $common->uploadToQiNiu($request, 'file_upload');
            if($res['status'] == 4403){
                 return $res['msg'];
            }
            $pic = "http://owv3oi69q.bkt.clouddn.com/".$res['data']['key'];
        }
        // dd($request->input('gname'));
        // $gname = "'".$request->input('gname')."'";
        // $unit = "'".$request->input('unit')."'";
        $launch_time = time();
        $bool =Goods::where('id', $id)
                     ->update([
                          'gname' => $request->input('gname'),
                          'goods_sn' => $request->input('goods_sn'),
                          'bid' =>   $request->input('bid'),
                          'sid' => $request->input('sid'),
                          'price' => $request->input('price'),
                          // 'unit' => $unit,
                          'click' => $request->input('click'),
                          'state' => $request ->input('state'),
                          'is_member_price' => $request ->input('is_member_price'),
                          'score' => $request ->input('score'),
                          'launch_time' =>$launch_time,
                          'pic' =>$pic,
                         ]);
         $info = Gdescr::where('id', $id)
                     ->update([
                            'descr' => $request->input('descr'),
                            'gid' =>$id,
                            'state' => $request ->input('state'),
                        ]);

        $search = new SearchController();
        $xunsearch =$search->updateToXunSearch($id);//将更新的数据添加到迅搜中

        // dd($xunsearch);
        if($bool&$info){
            Redis::del('lazyLoad:0');
            Redis::del('lazyLoad:1');
            Redis::del('lazyLoad:2');
            Redis::del('lazyLoad:3');
            Redis::del('lazyLoad:4');
            Redis::del('goodsData:'.$id);//删除之前的产品数据
            Redis::hDel('hotData', 'hotData:'.$id);
            return redirect('/Admin/goods')->with('msg', '修改成功');
        }
        
            return back()->with('errorTip', '修改失败,系统出错请稍后重试');
    }

    /**
     * 删除产品
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
       // dd($id);
        $res=Goods::where('id', $id)->delete();
        $info=Gdescr::where('pid', $id)->delete();
        $price=Gdetails_pic::where('gid', $id)->delete();
         if ($res&$info&$price) {
                Redis::del('lazyLoad:0');
                Redis::del('lazyLoad:1');
                Redis::del('lazyLoad:2');
                Redis::del('lazyLoad:3');
                Redis::del('lazyLoad:4');
                Redis::hDel('hotData', 'hotData:'.$id);
                $data = [
                           'status' => 0,
                           'msg'    =>'删除成功',
                           ];
             } else {
                 $data = [
                           'status' => 1,
                           'msg'    =>'删除失败,请稍后再试！',
                           ];
            }
        return $data;
     }

   

    /**
     * 产品规格属性的添加页面
     * @param  获得产品的gid
     * 返回添加属性的页面和传递数据$good_info
     */
    public function addGoodAttributes($id)
    {
        // dd($id);
        $good_info = Goods::select('id', 'gname')->where('id', $id)->first();

        return view ("Admin/Goods/product-addGoodAttributes", ['good_info' => $good_info]);
    }
   

     /**
     * 执行添加此产品规格属性
     * @param  获得产品的数据
     * 返回添加成功/失败
     */
    public function insertAttributesToGoodsPrice(request $request)
    {
        $this->validate($request, [
            'color' => 'required',
            'size' => 'required|numeric|min:0|max:99',
            'price' => 'required|numeric|min:0|max:9999999.99',
            // 'discount_price' => 'required|numeric|min:0|max:9999999.99',
            'storage' => 'required|numeric|min:0|max:9999999',
            'sales' => 'required',
            'is_discount' => 'required',
        ],
        [
            'color.required' => '颜色必填',
            'size.required' => '尺寸必填',
            'size.numeric' => '尺寸必须是数字',
            'size.min' => '尺寸最少为0',
            'size.max' => '尺寸最大为0',
            'price.required' => '价格必填',
            'price.numeric' => '价格必须是数字',
            'price.min' => '价格最小为0',
            'price.max' => '价格最大为9999999.99',
            // 'discount_price.required' => '促销价格必填',
            // 'discount_price.numeric' => '促销必须是数字',
            // 'discount_price.min' => '促销价格最小为0',
            // 'discount_price.max' => '促销价格最大为9999999.99',
            'storage.required' => '库存必填',
            'storage.numeric' => '库存必须是数字',
            'storage.min' => '库存最小位0',
            'storage.max' => '库存最大为9999999',
            'sales.required' => '销量必填',
            'is_discount.required' => '是否促销必填',

        ]);
        $bool = Gprice::insert([
            'gid'=> $request->input('gid'),
            'color' => $request->input('color'),
            'size' =>$request->input('size'),
            'price' =>$request->input('price'),
            'discount_price' =>$request->input('price'),
            'storage' =>$request->input('storage'),
            'sales' =>$request->input('sales'),
            'is_discount' =>2,
            'created_at' => date('Y-m-d H:i:s', time()),
            'updated_at' => date('Y-m-d H:i:s', time()),
          ]);

          if ($bool) {
            return redirect('/Admin/goods')->with('msg', '增加成功');
          }
          return back()->with('errorTip', '增加失败');
    }

    /**
     * 显示该产品所有图片的页面
     * @param  获得产品的gid
     * 返回
     */
    public function  showPhoto($id)
    {

        // dd($id);
        $res = Goods::select('goods_show.id', 'gname', 'path', 'goods_show.state','gid')
                    ->join('goods_show', 'goods_show.gid', '=', 'goods.id')
                    ->where('goods.id', $id)
                    ->paginate(10);
       
        // dd($res);
        return view ("Admin/Goods/product-photolist",['res' => $res]);
    }

    /**
     * 添加此产品的图片，包括细节图，详情页图
     * @param  获得产品的gid
     */
    public function  addGoodPhoto($id)
    {

        // dd($id);
        $res=Goods::select('id','gname', 'bid','sid')->where('id', $id)->first();
        // dd($res);
        return view ("Admin/Goods/product-photo",['res' => $res]);
    }

    /**
     * 执行上传此产品的图片，包括细节图，详情页图
     * @param  获得产品的数据
     * return 成功/失败
     */
    public function  uploadGoodPhoto(Request $request)
    {
        // dd($request);
        $common = new CommonApi;
        $res = $common->uploadToQiNiu($request, 'file_upload');
         if($res['status'] == 4403){
                 return $res['msg'];
            }
        $pic = "http://owv3oi69q.bkt.clouddn.com/".$res['data']['key'];
       
        $Gshow = Gshow::insert([
                'gid' => $request ->input('gid'),
                'state' => $request ->input('state'),
                'path' => $pic,
                'descr' => $request ->input('descr'),
                'created_at' => date('Y-m-d H:i:s', time()),
                'updated_at' => date('Y-m-d H:i:s', time()),
            ]);
        $Gdetails_pic = Gdetails_pic::insert([
                'gid' => $request ->input('gid'),
                'state' => $request ->input('state'),
                'path' => $pic,
                'descr' => $request ->input('descr'),
                'created_at' => date('Y-m-d H:i:s', time()),
                'updated_at' => date('Y-m-d H:i:s', time()),
            ]);
        if($Gshow & $Gdetails_pic){

            return redirect('Admin/goods')->with('msg', '添加成功');

        }else{

            return back()->with('errorTip', '添加失败');

        }
    }

  
  



    /**
     * @author mais <[<380354618@qq.com>]>
     */
    public function turnShowPic(Request $request)
    {
        //商品ID
        $gid = $request->id;

        $list = Carousels::get();

        return view('Admin/Goods/product-turnshowpic', ['list'=>$list,'ggid'=>$gid]);
    }

    public function turnShowPicEdit(Request $request)
    {
        // dd($request->all());
        $pic = '';

        //轮播图id
        $turnshowpicid = $request->brandclass;
        //商品ID
        $gid = $request->ggid;

        $common = new CommonApi;

        $res = $common->uploadToQiNiu($request, 'uploadfile');

        //判断是否有图  
        if(isset($res['data']['key'])){

                $pic = $res['data']['key'];
        }

        //有图就保存七牛云返回的路径,没有既$pic等于空
        if($pic){

            $pic = "http://owv3oi69q.bkt.clouddn.com/".$pic;

        }

        //七牛云返回的路径
        

        $mod = Carousels::find($turnshowpicid);

        $mod->gid = $gid;
        $mod->path = $pic;

        $ret = $mod->save();

        Redis::del('indexCarousels');

        $list = Carousels::get();

        return redirect()->action('Admin\Goods\GoodsController@turnShowPic', ['id' => 1]);
    }

}

